import {
  getUserCart,
  updateCountItem,
  removeItem,
  selectCartProduct,
  addCart
} from "@/api/mall/client/cart/cart";
import { getToken, setToken, removeToken } from '@/utils/auth'
import { defineStore } from "pinia";

const useCartStore = defineStore(
    'cart',
    {
        state: () => ({
          cartList: [],
          countNum: 0, // 数量
          totalAmount: 0,
          reduce: null,
          countType: 0
        }),
        actions: {
            // 获取cart信息
            getCartInfo() {
                return new Promise((resolve, reject) => {
                    if (getToken()) {
                        getUserCart().then(res => {
                            this.cartList = res.data.items;
                            this.totalAmount = res.data.totalAmount;
                            this.countNum = res.data.countNum;
                            this.countType = res.data.countType;
                            this.reduce = res.data.reduce;
                            resolve()
                        }).catch(error => {
                            reject(error)
                        })
                    }
                    
                })
            },
            // 删除cart
            removeCartItem(item) {
                return new Promise((resolve, reject) => {
                    removeItem({skuId: item.skuId, num: item.count}).then( res => {
                        this.getCartInfo();
                        resolve()
                    }).catch(() => {
                        reject(error)
                    })
                })
            },
            // 添加购物车
            addCart(item) {
                return new Promise((resolve, reject) => {
                    addCart(item).then( res => {
                        this.getCartInfo();
                        resolve()
                    }).catch(() => {
                        reject(error)
                    })
                })
            }
        }
    }
)

export default useCartStore